import RPi.GPIO as GPIO
import time

def getDistance(trig_pin, echo_pin):
    # 设置GPIO模式为BCM
    GPIO.setmode(GPIO.BCM)

    # 设置超声波传感器的引脚
    trig_pin = trig_pin
    echo_pin = echo_pin

    # 设置GPIO引脚模式
    GPIO.setup(trig_pin, GPIO.OUT)
    GPIO.setup(echo_pin, GPIO.IN)

    # print(GPIO.OUT,GPIO.IN)


    # 发送触发信号
    GPIO.output(trig_pin, GPIO.HIGH)
    time.sleep(0.00001)
    GPIO.output(trig_pin, GPIO.LOW)

    # 等待回应信号
    while GPIO.input(echo_pin) == GPIO.LOW:
        pulse_start_time = time.time()

    while GPIO.input(echo_pin) == GPIO.HIGH:
        pulse_end_time = time.time()

    # 计算距离
    pulse_duration = pulse_end_time - pulse_start_time
    distance = round(pulse_duration * 17150, 2)

    return distance

